<?php

namespace app\api\controller;

use app\api\model\Wxapp as WxappModel;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\library\wechat\WxPay;
use think\Cache;
use think\Db;
use app\common\service\Order as OrderService;
use app\api\service\orderanswer\PaySuccess;
use app\common\enum\order\PayType as PayTypeEnum;

/** 问答类 */
class Askanswer extends Controller
{
    /** 试题分类列表 */
    public function qaType()
    {
        // 分类模板
        $templet = array('category_style'=>20, 'share_title'=>'答题赚积分 题库大厅');
        //print_r($this->wxapp_id);
        if (!Cache::get('qatype_' . $this->wxapp_id)) {
            // 分类列表
            $res = Db::name('qa_type')->where(['qt_show'=>1,'wxapp_id'=>$this->wxapp_id])->order(['qt_sort'=>'asc','qt_id'=>'asc'])->select()->toArray();
            $list = [];
            foreach ($res as $value1){
                if($value1['qt_pid']==0){
                    $perArr['category_id'] = $value1['qt_id'];
                    $perArr['name'] = $value1['qt_name'];
                    $perArr['parent_id'] = $value1['qt_pid'];
                    $perArr['shows'] = 0;
                    $perArr['child'] = [];
                    foreach ($res as $value2){
                        if($value2['qt_pid']==$value1['qt_id']){
                            $sonArr['category_id'] = $value2['qt_id'];
                            $sonArr['name'] = $value2['qt_name'];
                            $sonArr['parent_id'] = $value2['qt_pid'];
                            $sonArr['shows'] = 0;
                            $perArr['child'][] = $sonArr;
                        }
                    }
                    $list[] = $perArr;
                }
            }
            Cache::tag('cache')->set('qatype_' . $this->wxapp_id, $list);
        }
        $list = Cache::get('qatype_' . $this->wxapp_id);
//        echo '<pre>';
//        print_r($list);
        return $this->renderSuccess(compact('templet', 'list'));
    }

    /** 获取每个分类下的试卷列表 */
    public function qaboxList(){
        $paramArr = $this->request->param();
        $page = $paramArr['page'];
        $userId = $paramArr['userId'];
        $where = "where aa.bq_show=1";
        $paramArr['type1']>0 ? $where .= " and aa.bq_type1=".$paramArr['type1'] : "";
        $paramArr['type2']>0 ? $where .= " and aa.bq_type2=".$paramArr['type2'] : "";
        $where .= " and bb.buy_qa_id is null ";

        $order = "order by aa.bq_id asc";
        $limit = "limit ".($page-1)*$this::PER_PAGE_NUM.", ".$this::PER_PAGE_NUM;
        // $sql = "select * from ".getTable('qa_boxquestion')." $where $limit";
        // 此人已购买的试卷就不查询了
        $user = Db::name('user')->where('user_id', $userId)->find();
        $uid = $user['user_id'];
        $sql = "select * from ".getTable('qa_boxquestion')." aa left join ".getTable('qa_buyquestion')." bb on aa.bq_id=bb.buy_qa_id and bb.buy_uid=$uid $where $order $limit";
        $list = Db::query($sql);
        return $this->renderSuccess(compact('list'));
    }

    /** 获取我购买的试卷列表 */
    public function myQaList(){
        $paramArr = $this->request->param();
        $page = $paramArr['page'];
        $dataType = $paramArr['dataType'];
        // mmmodify 参数true，可以传递给前台未找到，执行弹出登录框的动作
        $user = $this->getUser(true)->toArray();   // mmmodify 获取用户信息，参数false不弹出提示是否可以找到

        $limit = "limit ".($page-1)*$this::PER_PAGE_NUM.", ".$this::PER_PAGE_NUM;
        $where = "where (buy_uid=".$user['user_id']." or from_uid=".$user['user_id'].")";
        //$dataType>0 ? $where .= " and box_status=".$dataType : "";
        //可赠送的试题 box_status=1处女状态，未答题未赠送
        if($dataType==1){
            $where .= "and box_status=1 and buy_uid=".$user['user_id']." and ans_money_score<100";
        }
        //可回答可赠送的试题
        if($dataType==2){
            $where .= " and buy_uid=".$user['user_id']." and ans_money_score<100";
        }
        //已答题，可以重复回答的题，已经得到满分的题
        if($dataType==3){
            $where .= " and buy_uid=".$user['user_id']." and ans_money_score=100";
        }
        //已送出，我送别人的
        if($dataType==5){
            $where = "where from_uid>0 and from_uid=".$user['user_id'];
        }
        //送我的，朋友送给我的
        if($dataType==7){
            $where = "where from_uid>0 and buy_uid=".$user['user_id']." and from_uid!=".$user['user_id'];
        }
        $order = "order by buy_id desc";

        $sql = "select * from ".getTable('qa_buyquestion')." $where $order $limit";
        $list = Db::query($sql);
        return $this->renderSuccess(compact('list'));
    }

    /** 根据checkIdsStr获取提交订单中的试卷列表 */
    public function qbBoxListByOrder(){
        $paramArr = $this->request->param();
        $checkIdsStr = $paramArr['checkIdsStr'];
        $checkIdsArr = explode(",", $checkIdsStr);
        //pre($checkIdsArr);
        $list = Db::name('qa_boxquestion')->whereIn('bq_id', $checkIdsArr)->select()->toArray();
        //请求一下用户数据，应该实例化用户模型即可
        $user = $this->getUser(true)->toArray();
        //pre($user);
        return $this->renderSuccess(compact('list','user'));
    }

    /** 提交订单下单 */
    public function submitQaOrder(){
        $paramArr = $this->request->param();
        $checkIdsStr = trim($paramArr['checkIdsStr']);
        $checkIdsArr = explode(",", $checkIdsStr);
        //pre($checkIdsArr);
        if(count($checkIdsArr)>0 && $checkIdsStr){
            //$needMoney = count($checkIdsArr) * $this::QA_PRICE;
            $sql = "select sum(bq_price) as needMoney from ".getTable('qa_boxquestion')." where bq_id in ($checkIdsStr)";
            $res = Db::query($sql);
            $needMoney = $res[0]['needMoney'];

            $user = $this->getUser(true)->toArray();

            $useYUmoney = 0;
            $useWXmoney = $needMoney;
            // 判断余额是否充足
            $balance = $user['balance'];
            if($balance >= $needMoney){
                $useYUmoney = $needMoney;
                $useWXmoney = 0;
            }
            if($balance < $needMoney){
                $useYUmoney = $balance;
                $useWXmoney = floatMathFun($needMoney, $balance , "-");
            }
            $inArr = array();
            $orderNo = 'bqa_'.OrderService::createOrderNo();    // 回调通过订单前缀去判断
            $inArr['ord_uid'] = $user['user_id'];
            $inArr['ord_unick'] = $user['nickName'];
            $inArr['ord_uheader'] = $user['avatarUrl'];
            $inArr['ord_order'] = $orderNo;
            $inArr['ord_qa_ids'] = implode(",", $checkIdsArr);
            $inArr['ord_need_money'] = $needMoney;
            $inArr['ord_yu_money'] = $useYUmoney;
            $inArr['ord_wx_money'] = $useWXmoney;
//            $inArr['ord_status'] = $useWXmoney==0 ? 8 : 0;
            $inArr['ord_remark'] = "购买试卷";
            $inArr['wxapp_id'] = $this->wxapp_id;
            $inArr['ord_addtime_str'] = date('Y-m-d H:i:s',time());
            //pre($inArr);
            $ordID = Db::name('qa_buyorder')->insertGetId($inArr);
            // 如果使用余额支付
            if($useWXmoney==0){
                // 修改订单支付状态，执行试卷购买成功后的逻辑
                $payOkClass = new PaySuccess($orderNo);
                $payOk = $payOkClass->onPaySuccess(PayTypeEnum::BALANCE);
                // 返回结算信息
                return $this->renderSuccess([
                    'order_id' => $ordID,   // 订单id
                    'pay_type' => 10,  // 支付方式
                ], ['success' => '余额支付成功', 'error' => '余额支付失败']);
            }
            // 唤醒微信支付参数给前端
            else{
                $newUserObj = Db::name('user')->where('user_id', $user['user_id'])->find();
                // 统一下单API
                $wxConfig = WxappModel::getWxappCache($this->wxapp_id);
                $WxPay = new WxPay($wxConfig);
                $payment = $WxPay->unifiedorder($orderNo, $newUserObj['open_id'], $useWXmoney, OrderTypeEnum::ANSWER);
                // 返回结算信息
                return $this->renderSuccess([
                    'order_id' => $ordID,   // 订单id
                    'pay_type' => 20,  // 支付方式
                    'payment' => $payment               // 微信支付参数
                ], ['success' => '支付成功', 'error' => '订单未支付']);
            }
        }
        else{
            return $this->renderError('缺少支付参数');
        }
    }
    /** 提交订单下单 */
    public function getAllQestion(){
        $paramArr = $this->request->param();
        $qaid = trim($paramArr['qaid']);
        if($qaid>0){
            $list = Db::name('qa_perquestion')->where(['pq_pid'=>$qaid, 'pq_show'=>1])->select()->toArray();
            if(count($list)==0){
                return $this->renderError('该试卷还没录入任何考题');
            }
            $qaObj = Db::name('qa_boxquestion')->where('bq_id', $qaid)->find();
            return $this->renderSuccess(compact('list', 'qaObj'));
        }
        else{
            return $this->renderError('缺少问答id参数');
        }
    }
    /** 赠送好友试卷前，先通过好友ID查找好友 */
    public function getFriendObj(){
        $paramArr = $this->request->param();
        $fuid = trim($paramArr['fuid']);

        $user = $this->getUser(true)->toArray();

        $friendObj = Db::name('user')->where('user_id', $fuid)->find();
        if(!$friendObj){
            $friendObj = null;
        }
        else{
            if($user['user_id'] == $fuid){
                $friendObj = -1;
            }
        }
        return $this->renderSuccess(compact('friendObj'));
    }

    /** 执行赠送好友试卷操作 */
    public function sendQaToFriend(){
        $paramArr = $this->request->param();
        $buyid = trim($paramArr['buyid']);
        $frienduid = trim($paramArr['frienduid']);

        $friendObj = Db::name('user')->where('user_id', $frienduid)->find();
        if(!$friendObj){
            return $this->renderError('未找到好友');
        }
        else{
            $buyQaObj = Db::name('qa_buyquestion')->where('buy_id', $buyid)->find();
            if(!$friendObj){
                return $this->renderError('未找到该试卷');
            }
            else{
                $user = $this->getUser(true)->toArray();
                if($user['user_id']==$frienduid){
                    return $this->renderError('自己不能送试卷给自己');
                }
                else{
                    $upArr['buy_uid'] = $friendObj['user_id'];
                    $upArr['buy_unick'] = $friendObj['nickName'];
                    $upArr['buy_uheader'] = $friendObj['avatarUrl'];
                    $upArr['from_uid'] = $user['user_id'];
                    $upArr['from_unick'] = $user['nickName'];
                    $upArr['from_uheader'] = $user['avatarUrl'];
                    $upArr['box_status'] = 5;
                    $upArr['box_send_status'] = 1;  //恢复试卷正常可使用状态
                    $upArr['from_timestr'] = date('Y-m-d H:i:s', time());
                    Db::name('qa_buyquestion')->where('buy_id',$buyid)->update($upArr);

                    return $this->renderSuccess(compact('buyQaObj'));
                }
            }
        }
    }
    /** 随机获取商品图片 */
    public function getRandGoodImg(){
        $sql = "select aa.image_id,aa.net_name,aa.goods_price,bb.file_img_allpath from zj_goods_sku aa left join zj_upload_file bb on aa.image_id=bb.file_id where bb.file_img_allpath!='' and aa.goods_price<10 and bb.back_goodid>=4625 and bb.back_goodid<=4671 and bb.group_id=4 ORDER BY RAND() limit 6";
        $list = Db::query($sql);
        return $this->renderSuccess(compact('list'));
    }
    /** 设置问答进入赠送中的环节 */
    public function qaSending(){
        $paramArr = $this->request->param();
        $qaid = trim($paramArr['qaid']);
        $buyid = trim($paramArr['buyid']);
        $upArr['box_send_status'] = 1;
        if($buyid>0){
            $upArr['box_send_status'] = 4;
            Db::name('qa_buyquestion')->where('buy_id',$buyid)->update($upArr);
        }
        return $this->renderSuccess(compact('upArr'));
    }
    /** 分享形式 执行赠送好友试卷操作 */
    public function getSendQaByShare(){
        $paramArr = $this->request->param();
        $qaid = trim($paramArr['qaid']);
        $showPPP = isset($paramArr['showPPP']) ? trim($paramArr['showPPP']) : 'yes';
        $inLine = trim($paramArr['inLine']);    // 当值为yes的时候，代表直接通过扫码采单，赠送该套试题
        $buyid = trim($paramArr['buyid']);
        $senduid = trim($paramArr['senduid']);  //谁转发的试卷，试卷原始拥有人
        $myuid = trim($paramArr['myuid']);      //转发我收到，由senduid送给我
        $back = ['msg'=>'','state'=>''];

        //前期免费送试卷
        if($showPPP=='no'){
            return $this->giftSongQa($myuid, $qaid, $buyid);
        }
        else{
            $sendObj = Db::name('user')->where('user_id', $senduid)->find();
            if(!$sendObj){
                $back['msg'] = '未找到赠送人';
                return $this->renderSuccess(compact('back'));
            }
            else{
                $user = Db::name('user')->where('user_id', $myuid)->find();
                //如果是采单进线模式的赠送题，先获取手机号再送题，然后减扣商户余额
                //目前这批传单上的扫码，目前扫码转移到custom自定义小程序页面中，后期此出作废
                if($inLine=='yes'){
                    $back = $this->inlineGetQa($sendObj, $user, $qaid, $back);
                    return $this->renderSuccess(compact('back'));
                }
                //如果是好友已经买号的题赠送给我
                else{
                    $buyQaObj = Db::name('qa_buyquestion')->where('buy_id', $buyid)->find();
                    if(!$buyQaObj){
                        $back['msg'] = '未找到该问答订单';
                        return $this->renderSuccess(compact('back'));
                    }
                    else{
                        if($senduid==$myuid){
                            $back['msg'] = '自己无法领取自己的问答哟';
                            return $this->renderSuccess(compact('back'));
                        }
                        else{
                            if($buyQaObj['box_send_status']==1){
                                if($buyQaObj['buy_uid']==$myuid){
                                    $back['msg'] = '该问答您已经领取过了';
                                }
                                else{
                                    $back['msg'] = '该问答已经送出';
                                }
                                return $this->renderSuccess(compact('back'));
                            }
                            else{
                                if($buyQaObj['from_uid']>0){
                                    $back['msg'] = '该问答已被别人抢先领取了';
                                    return $this->renderSuccess(compact('back'));
                                }
                                else{
                                    $upArr['buy_uid'] = $user['user_id'];
                                    $upArr['buy_unick'] = $user['nickName'];
                                    $upArr['buy_uheader'] = $user['avatarUrl'];
                                    $upArr['from_uid'] = $sendObj['user_id'];
                                    $upArr['from_unick'] = $sendObj['nickName'];
                                    $upArr['from_uheader'] = $sendObj['avatarUrl'];
                                    $upArr['box_status'] = 5;
                                    $upArr['box_send_status'] = 1;  //恢复试卷正常可使用状态
                                    $upArr['from_timestr'] = date('Y-m-d H:i:s', time());
                                    Db::name('qa_buyquestion')->where('buy_id',$buyid)->update($upArr);
                                    $back['state'] = 'sendOk';
                                    $back['newBuyid'] = 0;  //还是沿用分享时候的购买id
                                    $back['msg'] = '系统已自动为您领取了该问答';
                                    return $this->renderSuccess(compact('back'));
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /**点击试卷，小于指定积分的时候，直接送整套试卷*/
    private function giftSongQa($uid, $qaID, $buyId){
        //1. 检测积分是否已经超过免费金额
        $userObj = Db::name('user')->where('user_id', $uid)->find();
        $allGetJifen = $userObj['allsend_points'];
        $wxappObj = Db::name('wxapp_navbar')->where('wxapp_id', $this->wxapp_id)->find();
        $maxSongJifen = $wxappObj['max_gift_jifen'];
        if($userObj && $wxappObj){
            if($allGetJifen>=$maxSongJifen){
                $back['msg'] = '您的免费额度'.$maxSongJifen.'积分已送完，请购买后再答题送积分';
                return $this->renderSuccess(compact('back'));
            }
            else{
                if($buyId>0){
                    $buyQaObj = Db::name('qa_buyquestion')->where(['buy_id'=>$buyId])->find();
                }
                else{
                    $buyQaObj = Db::name('qa_buyquestion')->where(['buy_uid'=>$uid, 'buy_qa_id'=>$qaID])->find();
                }
                if($buyQaObj){
                    $back['state'] = 'sendOk';
                    $back['newBuyid'] = $buyQaObj['buy_id'];
                    $back['msg'] = '已经领过，继续答题';
                    return $this->renderSuccess(compact('back'));
                }
                else{
                    $inArr['buy_uid'] = $userObj['user_id'];
                    $inArr['buy_unick'] = $userObj['nickName'];
                    $inArr['buy_uheader'] = $userObj['avatarUrl'];
                    $inArr['buy_qa_id'] = $qaID;
                    $qaObj = Db::name('qa_boxquestion')->where('bq_id', $qaID)->find();
                    $inArr['buy_qa_title'] = $qaObj['bq_title'];
                    $inArr['buy_qa_price'] = $qaObj['bq_price'];
                    $inArr['buy_alljifen'] = $qaObj['bq_perjifen'] * $qaObj['bq_num'];
                    $inArr['buy_qa_des'] = $qaObj['bq_des'];
                    $inArr['buy_easy'] = $qaObj['bq_easy'];
                    $inArr['buy_qa_num'] = $qaObj['bq_num'];
                    $inArr['wxapp_id'] = $this->wxapp_id;
                    $inArr['buy_addtime_str'] = date('Y-m-d H:i:s',time());
                    $buyid = Db::name('qa_buyquestion')->insertGetId($inArr);
                    $back['state'] = 'sendOk';
                    $back['newBuyid'] = $buyid;
                    $back['msg'] = '领取成功，开始答题';
                    return $this->renderSuccess(compact('back'));
                }
            }
        }
        else{
            $back['msg'] = '未找到该用户';
            return $this->renderSuccess(compact('back'));
        }
    }

    /**采单形式赠送试题的逻辑处理*/
    private function inlineGetQa($sendObj, $user, $qaid, $back){
        //0. 判断赠送人是否为地推人员，是否为代理商
        //1. 查找代理商信息，判断代理商余额
        //2. 查找本套问答试卷的金额，如果代理商余额小于试卷金额，无法赠送提示不足
        //3.0. 入库前的判断，先判断该用户是否领取过该试卷
        if($sendObj['user_id'] == $user['user_id']){
            $back['msg'] = '自己无法领取自己的问答哟';
        }
        else{
            $qaObj = Db::name('qa_buyquestion')->where(['buy_qa_id'=>$qaid, 'buy_uid'=>$user['user_id']])->find();
            if($qaObj){
                $back['msg'] = '您已经领取过该问答了';
            }
            else{
                //3.1. 如果代理商余额充足，添加要赠送的试卷入库
                $inArr['buy_uid'] = $user['user_id'];
                $inArr['buy_unick'] = $user['nickName'];
                $inArr['buy_uheader'] = $user['avatarUrl'];
                $inArr['buy_qa_id'] = $qaid;
                $qaObj = Db::name('qa_boxquestion')->where('bq_id', $qaid)->find();
                $inArr['buy_qa_title'] = $qaObj['bq_title'];
                $inArr['buy_qa_price'] = $qaObj['bq_price'];
                $inArr['buy_alljifen'] = $qaObj['bq_perjifen'] * $qaObj['bq_num'];
                $inArr['buy_qa_des'] = $qaObj['bq_des'];
                $inArr['buy_easy'] = $qaObj['bq_easy'];
                $inArr['buy_qa_num'] = $qaObj['bq_num'];
                $inArr['wxapp_id'] = $this->wxapp_id;
                $inArr['buy_addtime_str'] = date('Y-m-d H:i:s',time());

                $inArr['from_uid'] = $sendObj['user_id'];
                $inArr['from_unick'] = $sendObj['nickName'];
                $inArr['from_uheader'] = $sendObj['avatarUrl'];
                $inArr['box_status'] = 5;

                $buyid = Db::name('qa_buyquestion')->insertGetId($inArr);

                $back['state'] = 'sendOk';
                $back['newBuyid'] = $buyid;
                $back['msg'] = '问答领取成功，自动进入答题';
            }
        }
        //3.3. 扣除代理商余额，记录余额减少记录

        return $back;
    }

    /**获取答题排行*/
    public function getpaihang(){
        $list = [];
        return $this->renderSuccess(compact('list'));
    }
}
